<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
    <style>
        /* 基础样式 */
        body {
            margin: 0;
            padding: 0;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
            color: #333;
            background-color: #f5f7fa;
        }

        /* 主内容区 */
        .main-content {
            background-color: #f5f7fa;
            overflow: auto;
            padding: 20px;
        }

        /* 商品展示区 */
        .section-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 20px;
            color: #333;
            padding-bottom: 10px;
            border-bottom: 1px solid #e6e6e6;
        }

        .product-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .product-card {
            background-color: white;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;
        }

        .product-card:hover {
            transform: translateY(-5px);
        }

        .product-img {
            width: 100%;
            height: 160px;
            object-fit: contain;
            background-color: #f5f7fa;
        }

        .product-info {
            padding: 15px;
        }

        .product-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .product-number {
            font-size: 12px;
            color: #999;
            margin-bottom: 10px;
        }

        .product-price {
            font-size: 16px;
            color: #f56c6c;
            font-weight: bold;
        }

        .add-to-cart {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #409EFF;
            color: white;
            padding: 8px 0;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .add-to-cart:hover {
            background-color: #66b1ff;
        }

        /* 搜索区域 */
        .search-container {
            background-color: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .search-input {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .search-input input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            outline: none;
        }

        .search-input button {
            padding: 10px 20px;
            background-color: #409EFF;
            color: white;
            border: none;
            border-radius: 4px;
            margin-left: 10px;
            cursor: pointer;
        }

        .hot-search {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .hot-search-item {
            font-size: 12px;
            color: #666;
            cursor: pointer;
        }

        .hot-search-item:hover {
            color: #409EFF;
        }

        /* 轮播图样式 */
        .carousel-container {
            margin-bottom: 20px;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .el-carousel {
            position: relative;
            overflow: hidden;
            height: 300px;
        }

        .el-carousel__container {
            position: relative;
            height: 100%;
        }

        .el-carousel__item {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            transition: opacity 0.5s ease;
            opacity: 0;
        }

        .el-carousel__item.active {
            opacity: 1;
        }

        .carousel-link {
            display: block;
            width: 100%;
            height: 100%;
            position: relative;
        }

        .carousel-caption {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            padding: 10px 15px;
            border-radius: 4px;
            font-size: 16px;
        }

        .el-carousel__indicators {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 8px;
        }

        .el-carousel__indicators button {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            border: none;
            background-color: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            padding: 0;
        }

        .el-carousel__indicators button.is-active {
            background-color: #409EFF;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 轮播图区域 -->
        <div class="carousel-container">
            <div class="el-carousel" v-if="carousels.length > 0">
                <div class="el-carousel__container">
                    <div class="el-carousel__item" v-for="(item, index) in carousels" :key="index"
                         :style="{ backgroundImage: 'url(' + item.imageUrl + ')' }">
                        <a :href="item.link" class="carousel-link">
                            <div class="carousel-caption" v-if="item.captionText">
                                {{ item.captionText }}
                            </div>
                        </a>
                    </div>
                </div>
                <div class="el-carousel__indicators">
                    <button v-for="(item, index) in carousels" :key="index"
                            :class="{ 'is-active': currentCarouselIndex === index }"
                            @click="goToCarousel(index)"></button>
                </div>
            </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container">
            <div class="search-input">
                <input type="text"
                       placeholder="请输入关键词"
                       v-model="searchKeyword"
                       @keyup.enter="searchProducts">
                <button @click="searchProducts">搜索</button>
            </div>
            <div class="hot-search">
                <div class="hot-search-item">常用搜索 :</div>
                <div class="hot-search-item"
                     v-for="(item, index) in hotKeywords"
                     :key="index"
                     @click="searchByKeyword(item)">
                    {{ item }}
                </div>
            </div>
        </div>

        <!-- 新品推荐 -->
        <div class="section-title">新品推荐</div>
        <div class="product-container">
            <div class="product-card" v-for="item in newProducts" :key="item.id">
                <img :src="item.image" class="product-img" alt=""  @click="goToProductDetail(item.id)">
                <div class="product-info" >
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-number">{{ item.number }}</div>
                    <div class="product-price">￥{{ item.price }}</div>
                </div>
                <div class="add-to-cart" @click="handleAddCart(item)">
                    <i class="el-icon-shopping-cart-2"></i>
                    <span>加入购物车</span>
                </div>
            </div>
        </div>

        <!-- 精品推荐 -->
        <div class="section-title">精品推荐</div>
        <div class="product-container">
            <div class="product-card" v-for="item in featuredProducts" :key="item.id" >
                <img :src="item.image" class="product-img" alt="" @click="goToProductDetail(item.id)">
                <div class="product-info">
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-number">{{ item.number }}</div>
                    <div class="product-price">￥{{ item.price }}</div>
                </div>
                <div class="add-to-cart" @click="handleAddCart(item)">
                    <i class="el-icon-shopping-cart-2"></i>
                    <span>加入购物车</span>
                </div>
            </div>
        </div>

        <!-- 超值推荐 -->
        <div class="section-title">超值推荐</div>
        <div class="product-container">
            <div class="product-card" v-for="item in valueProducts" :key="item.id" >
                <img :src="item.image" class="product-img" alt="" @click="goToProductDetail(item.id)">
                <div class="product-info">
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-number">{{ item.number }}</div>
                    <div class="product-price">￥{{ item.price }}</div>
                </div>
                <div class="add-to-cart" @click="handleAddCart(item)">
                    <i class="el-icon-shopping-cart-2"></i>
                    <span>加入购物车</span>
                </div>
            </div>
        </div>

        <!-- 装置专区 -->
        <div class="section-title">装置专区</div>
        <div class="product-container">
            <div class="product-card" v-for="item in deviceProducts" :key="item.id" >
                <img :src="item.image" class="product-img" alt="" @click="goToProductDetail(item.id)">
                <div class="product-info">
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-number">{{ item.number }}</div>
                    <div class="product-price">￥{{ item.price }}</div>
                </div>
                <div class="add-to-cart" @click="handleAddCart(item)">
                    <i class="el-icon-shopping-cart-2"></i>
                    <span>加入购物车</span>
                </div>
            </div>
        </div>

        <!-- 活动专区 -->
        <div class="section-title">活动专区</div>
        <div class="product-container">
            <div class="product-card" v-for="item in promotionProducts" :key="item.id">
                <img :src="item.image" class="product-img" alt="" @click="goToProductDetail(item.id)">
                <div class="product-info">
                    <div class="product-name">{{ item.name }}</div>
                    <div class="product-number">{{ item.number }}</div>
                    <div class="product-price">￥{{ item.price }}</div>
                </div>
                <div class="add-to-cart" @click="handleAddCart(item)">
                    <i class="el-icon-shopping-cart-2"></i>
                    <span>加入购物车</span>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data() {
            return {
                carousels: [
                    {
                        imageUrl: "https://jack-shop-sgp.oss-ap-southeast-1.aliyuncs.com/banner/banner1.jpg",
                        captionText: "新品缝纫机零件上市",
                        link: "/products/new",
                        sortOrder: 1
                    },
                    {
                        imageUrl: "https://jack-shop-sgp.oss-ap-southeast-1.aliyuncs.com/banner/banner2.jpg",
                        captionText: "限时特惠活动",
                        link: "/promotions",
                        sortOrder: 2
                    },
                    {
                        imageUrl: "https://jack-shop-sgp.oss-ap-southeast-1.aliyuncs.com/banner/banner3.jpg",
                        captionText: "专业缝纫机维修工具",
                        link: "/tools",
                        sortOrder: 3
                    }
                ],
                currentCarouselIndex: 0,
                carouselInterval: null,
                newProducts: [],
                featuredProducts: [],
                valueProducts: [],
                deviceProducts: [],
                promotionProducts: [],
                searchKeyword: '',
                hotKeywords: [
                    "平缝", "包缝", "剪刀", "C4",
                    "针板", "电磁铁", "压脚", "20717004",
                    "A4", "旋梭"
                ],
                searchResults: [],
                showSearchResults: false,
            };
        },
        methods: {
            startCarousel() {
                this.carouselInterval = setInterval(() => {
                    this.currentCarouselIndex = (this.currentCarouselIndex + 1) % this.carousels.length;
                    this.updateCarousel();
                }, 5000);
            },
            goToCarousel(index) {
                this.currentCarouselIndex = index;
                this.updateCarousel();
            },
            updateCarousel() {
                const items = document.querySelectorAll('.el-carousel__item');
                items.forEach((item, index) => {
                    if (index === this.currentCarouselIndex) {
                        item.classList.add('active');
                    } else {
                        item.classList.remove('active');
                    }
                });
            },
            // 获取轮播图数据
            fetchCarousels() {
                axios({
                    method: 'get',
                    url: '/category/carousels'
                }).then(resp => {
                    this.carousels = resp.data;
                    this.$nextTick(() => {
                        this.updateCarousel();
                    });
                }).catch(error => {
                    console.error('获取轮播图失败:', error);
                });
            },
            // 获取新品数据
            async fetchNewProducts() {
                try {
                    const resp = await axios.get('/product/new');
                    if (resp.data.code === 20041) {
                        // 使用Promise.all并行获取所有图片
                        const productsWithImages = await Promise.all(
                            resp.data.data.map(async product => ({
                                ...product,
                                id: product.productId,
                                name: product.productName,
                                number: product.productNumber,
                                price: product.price.toFixed(2),
                                image: await this.getProductImage(product.productId)
                            }))
                        );
                        this.newProducts = productsWithImages;
                    }
                } catch (error) {
                    console.error('获取新品失败:', error);
                }
            },
            // 获取推荐产品数据
            async fetchFeaturedProducts() {
                try {
                    const resp = await axios.get('/product/featured');
                    if (resp.data.code === 20041) {
                        const productsWithImages = await Promise.all(
                            resp.data.data.map(async product => ({
                                id: product.productId,
                                name: product.productName,
                                number: product.productNumber,
                                price: product.price.toFixed(2),
                                image: await this.getProductImage(product.productId)
                            }))
                        );
                        this.featuredProducts = productsWithImages;
                    }
                } catch (error) {
                    console.error('获取推荐产品失败:', error);
                    this.featuredProducts = []; // 确保有默认值
                }
            },

            // 获取价值产品数据
            async fetchValueProducts() {
                try {
                    const resp = await axios.get('/product/value');
                    if (resp.data.code === 20041) {
                        const productsWithImages = await Promise.all(
                            resp.data.data.map(async product => ({
                                id: product.productId,
                                name: product.productName,
                                number: product.productNumber,
                                price: product.price.toFixed(2),
                                image: await this.getProductImage(product.productId)
                            }))
                        );
                        this.valueProducts = productsWithImages;
                    }
                } catch (error) {
                    console.error('获取价值产品失败:', error);
                    this.valueProducts = [];
                }
            },

            // 获取设备产品数据
            async fetchDeviceProducts() {
                try {
                    const resp = await axios.get('/product/device');
                    if (resp.data.code === 20041) {
                        const productsWithImages = await Promise.all(
                            resp.data.data.map(async product => ({
                                id: product.productId,
                                name: product.productName,
                                number: product.productNumber,
                                price: product.price.toFixed(2),
                                image: await this.getProductImage(product.productId)
                            }))
                        );
                        this.deviceProducts = productsWithImages;
                    }
                } catch (error) {
                    console.error('获取设备产品失败:', error);
                    this.deviceProducts = [];
                }
            },

            // 获取促销产品数据
            async fetchPromotionProducts() {
                try {
                    const resp = await axios.get('/product/promotion');
                    if (resp.data.code === 20041) {
                        const productsWithImages = await Promise.all(
                            resp.data.data.map(async product => ({
                                id: product.productId,
                                name: product.productName,
                                number: product.productNumber,
                                price: product.price.toFixed(2),
                                image: await this.getProductImage(product.productId)
                            }))
                        );
                        this.promotionProducts = productsWithImages;
                    }
                } catch (error) {
                    console.error('获取促销产品失败:', error);
                    this.promotionProducts = [];
                }
            },
            // 获取产品图片
            async getProductImage(productId) {
                try {
                    const response = await axios.get('/product/image', {
                        params: { productId }
                    });
                    return response.data.data?.imageUrl || this.getDefaultImage();
                } catch (error) {
                    console.error('获取图片失败:', error);
                    return this.getDefaultImage();
                }
            },
            getDefaultImage() {
                return '../image/code.jpg';
            },
            // 搜索产品
            async searchProducts() {
                if (!this.searchKeyword.trim()) {
                    console.log('请输入搜索关键词');
                    return;
                }

                window.parent.postMessage({
                    type: 'changePage',
                    url: 'search-results.html',
                    params: { keyword: this.searchKeyword }
                }, '*');
            },

            // 点击热门关键词搜索
            searchByKeyword(keyword) {
                window.parent.postMessage({
                    type: 'changePage',
                    url: 'search-results.html',
                    params: { keyword }
                }, '*');
            },
            goToProductDetail(productId) {
                location.href = `products.html?productId=${productId}`;
                console.log('跳转到商品详情页:', productId);
            },
            async handleAddCart(item) {
                try {

                    // 显示加载状态
                    // this.$message.loading('正在添加到购物车...');

                    const cartItem = {
                        userId: product.userId,
                        productId: item.productId,
                        quantity: product.quantity
                    };
                    // 调用后端API
                    const response = await axios.post('/shoppingcarts/add', cartItem);

                    // 处理响应
                    if (response.data.code === 20011) {
                        this.$message.success('添加购物车成功');

                        // 可选：更新购物车数量指示器
                        // this.updateCartCount();

                        // 可选：延迟后关闭消息提示
                        setTimeout(() => {
                            this.$message.close();
                        }, 2000);
                    } else {
                        this.$message.error(response.data.msg || '添加购物车失败');
                    }
                } catch (error) {
                    console.error('添加购物车失败', error);
                    this.$message.error('网络错误，请稍后重试');
                }
            }
        },
        mounted() {
            window.addEventListener('message', (event) => {
                if (event.data.type === 'searchProduct') {
                    this.searchKeyword = event.data.keyword;
                    this.searchProducts();
                }
            });

            this.fetchCarousels();
            this.fetchNewProducts();
            this.fetchFeaturedProducts();
            this.fetchValueProducts();
            this.fetchDeviceProducts();
            this.fetchPromotionProducts();

            this.startCarousel();
            // 初始化显示第一张轮播图
            this.$nextTick(() => {
                this.updateCarousel();
            });
        },
        beforeDestroy() {
            if (this.carouselInterval) {
                clearInterval(this.carouselInterval);
            }
        }
    });
</script>
</html>